import { createRouter, createWebHistory } from 'vue-router'
import LoginView from '../views/LoginView.vue'
import PatientListView from '../views/PatientListView.vue'
import ImageViewer from '../components/image-viewer/ImageViewer.vue'
import EnhancedImageViewer from '../components/EnhancedImageViewer.vue'
import UploadTestView from '../views/UploadTestView.vue'
import MainView from '../views/mainview.vue'

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: LoginView
  }, 
  {
    path: '/main',
    name: 'Main',
    component: MainView,
    meta: { requiresAuth: true }
  },
  {
    path: '/patients',
    name: 'Patients',
    component: PatientListView,
    meta: { requiresAuth: true }
  },
  {
    path: '/upload-test',
    name: 'UploadTest',
    component: UploadTestView,
    meta: { requiresAuth: true }
  },
  {
    path: '/image-viewer/:patientId',
    name: 'ImageViewer',
    component: ImageViewer,
    props: true,
    meta: { requiresAuth: true }
  },
  {
    path: '/enhanced-image-viewer/:filename',
    name: 'EnhancedImageViewer',
    component: EnhancedImageViewer,
    props: true,
    meta: { requiresAuth: true }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 添加路由守卫
router.beforeEach((to, from, next) => {
  // 检查路由是否需要认证
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
  
  // 检查用户是否已认证
  const isAuthenticated = localStorage.getItem('isAuthenticated') === 'true' && 
                         localStorage.getItem('token')
  
  // 如果路由需要认证但用户未认证，则重定向到登录页面
  if (requiresAuth && !isAuthenticated) {
    next('/login')
  } 
  // 如果用户已认证且试图访问登录页面，则重定向到患者列表页面
  else if (to.path === '/login' && isAuthenticated) {
    next('/patients')
  } 
  // 其他情况允许访问
  else {
    next()
  }
})

export default router